package gd.hq.yolov5.comunicate;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

class BlueToothThread extends Thread {
    private static final UUID ECG_UUID = new UUID(1L,1L);
    BluetoothDevice device;
    BluetoothSocket socket;
    public BlueToothThread(BluetoothDevice device) {
        this.device = device;
    }

    @Override
    public void run() {
        try {
            Log.d("TAG", "连接蓝牙");
            socket = device.createRfcommSocketToServiceRecord(device.getUuids()[0].getUuid());
            //在连接过程中，会出现java.io.IOException: read failed, socket might                    closed or timeout, read ret: -1,目前还没什么找到太好的解决方案
            socket.connect();
            InputStream inputStream = null;
            OutputStream outputStream = null;
            if (socket != null) {
                Log.d("TAG", "获取输入流");
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();
            }
            outputStream.write("hhahaha".getBytes());
            outputStream.flush();
            byte[] bytes = new byte[100];
            if (inputStream != null) {
                while (true) {
                    int read = inputStream.read(bytes);
                    if(read>0){
                        String data = new String(bytes,"GB2312");
                        Log.d("read",data);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}